/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package session;

import Entity.Users;
import java.util.List;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

/**
 *
 * @author Cyn
 */
@Stateless
@LocalBean
public class BeanUsers {
    
    @PersistenceContext
    private EntityManager em;
    
    // Enregistrement d'un nouvel utilisateur
    public void creer( Users utilisateur ) {
        em.persist( utilisateur );
    }
    public Users update(Users u){
        em.merge(u);
        return u;
    }
    public void testdb(){
        creer(new Users("Vincent", "toto", "toto", "Vendeur"));
        creer(new Users("Jule", "titi", "titi", "Acheteur"));
        creer(new Users("Marc", "tutu", "tutu", "Vendeur"));
        creer(new Users("Ana", "tata", "tata", "Acheteur"));
    }
    
    public List<Users> getAllUsers(){
        Query query = em.createNamedQuery("Users.findAll");        
        return query.getResultList();
    }
    
    public Users authentification(String log, String pwd) {
        try
        {
            System.out.println("==Authentifier==");
            Query query = em.createQuery("select u from Users u where u.login =:login and u.pwd =:pass");
            query.setParameter("login", log);
            query.setParameter("pass", pwd);
            Users u = (Users) query.getSingleResult();
            System.out.println("login found"+u.getLogin());
            return u;
        }
        catch(Exception e)
        {
            return null;
        }
    }

    public List<Users> getVendeurs(String keyword) {
        try{
            Query query = em.createNamedQuery("Users.findVendeurs");
            query.setParameter("key", "%" + keyword + "%");
            query.setParameter("type", "Vendeur"); 
            return query.getResultList(); 
        }catch(Exception e){
            System.err.println("Aucun produit ne correspond au mot : "+keyword);
            return null;
        }
    }
    
}
